package alon.xmnn.bobing;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import alon.app.ini.IniFile;
import alon.app.itask.IBrowserLisener;
import alon.app.itask.TERequest;
import alon.app.itask.Task;
import alon.app.tools.UrlUtils;
public class BobingMain extends Task
{
	private static final long	serialVersionUID	= 2074398930361568345L;
	private Logger logInfo = Logger.getLogger("app.info");
	private Logger logError = Logger.getLogger("app.error");
	private String roomsUrl="";
	private String roomUrl="";
	private String roomsLogin;
	private String boUrl="";
    private String curRooms="";
    private Random rand=new Random();
    private NnAccount curUser;
    private String rooms;
    private IBrowserLisener getRoomsLisener;
    private IBrowserLisener enterRoomLisener;
    private IBrowserLisener roomloginLisener;
    private IBrowserLisener boyibaLisener;
    private int[] coreIndexs={0,1,2,3,4,5,6,11};
    private String[] zhuanyuan={"带一","带三","带五","带六","带七","带八","带九","带十","带十一","带十二"};
    private String[] wuzi={"带一","带二","带三","带五","带六"};
    private List<Integer> willCore=new ArrayList<Integer>();
    public BobingMain(NnAccount curUser,IniFile inifile)
    {
    	this.curUser=curUser;
    	setName("bobing_"+curUser.getUser());
    	setIniFile(inifile);
    }
    private void genCores(int tol,int cot){
		int x0=0,x1=0,x2=0,x3=0,x4=0,x5=0,x6=0;
		int x7=rand.nextInt(3);
		if(tol<=0){
			tol=900+rand.nextInt(50)*10;
			cot=70;
		}
		if(cot<=0){
			cot=70;
		}
		while((10*x1+20*x2+40*x3+60*x4+100*x5+200*x6+300*x7)<tol-100
				||(10*x1+20*x2+40*x3+60*x4+100*x5+200*x6+300*x7)>tol+100){
			x0=0;
			x6=rand.nextInt((tol-x7*300)/200>(cot-x0-x7)?(cot-x0-x7):(tol-x7*300)/200);
			x5=rand.nextInt((tol-x7*300-x6*200)/100>(cot-x0-x7-x6)?(cot-x0-x7-x6):(tol-x7*300-x6*200)/100);
			x4=rand.nextInt((tol-x7*300-x6*200-x5*100)/60>(cot-x0-x7-x6-x5)?(cot-x0-x7-x6-x5):(tol-x7*300-x6*200-x5*100)/60);
			x3=rand.nextInt((tol-x7*300-x6*200-x5*100-x4*60)/40>(cot-x0-x7-x6-x5-x4)?(cot-x0-x7-x6-x5-x4):(tol-x7*300-x6*200-x5*100-x4*60)/40);
			x2=rand.nextInt((tol-x7*300-x6*200-x5*100-x4*60-x3*40)/20>(cot-x0-x7-x6-x5-x4-x3)?(cot-x0-x7-x6-x5-x4-x3):(tol-x7*300-x6*200-x5*100-x4*60-x3*40)/20);
			x1=(cot-x0-x7-x6-x5-x4-x3-x2)/2+rand.nextInt(cot-x0-x7-x6-x5-x4-x3-x2/2);
			x0=cot-x7-x6-x5-x4-x3-x2-x1;
		}
		logInfo.info(curUser.getUser()+",预计博:"+(x0+x1+x2+x3+x4+x5+x6+x7)+"次,预计成绩:"+(10*x1+20*x2+40*x3+60*x4+100*x5+200*x6+300*x7));
		for(int i=0;i<x0;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[0]);
			}else{
				willCore.add(coreIndexs[0]);
			}
		}
		for(int i=0;i<x1;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[1]);
			}else{
				willCore.add(coreIndexs[1]);
			}
		}
		for(int i=0;i<x2;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[2]);
			}else{
				willCore.add(coreIndexs[2]);
			}
		}
		for(int i=0;i<x3;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[3]);
			}else{
				willCore.add(coreIndexs[3]);
			}
		}
		for(int i=0;i<x4;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[4]);
			}else{
				willCore.add(coreIndexs[4]);
			}
		}
		for(int i=0;i<x5;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[5]);
			}else{
				willCore.add(coreIndexs[5]);
			}
		}
		for(int i=0;i<x6;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[6]);
			}else{
				willCore.add(coreIndexs[6]);
			}
		}
		for(int i=0;x7>0 && i<x7;i++){
			if(willCore.size()!=0){
				willCore.add(rand.nextInt(willCore.size()),coreIndexs[7]);
			}else{
				willCore.add(coreIndexs[7]);
			}
		}
    }
	public void init() throws Exception
	{
		roomUrl=getConfValue("bobing", "roomUrl","http://bobing.xmnn.cn/unionpay/room.php?roomid=#rid");
		boUrl=getConfValue("bobing", "boUrl", "http://bobing.xmnn.cn/api/bbsave.php");
		roomsUrl=getConfValue("bobing", "roomsUrl","http://bobing.xmnn.cn/unionpay/mybobing.php");
		roomsLogin=getConfValue("bobing", "roomsLogin", "http://bbs.xmnn.cn/api/bobing.php");
		rooms=getConfValue("bobing", "rooms","");
		initLiseners();
	}
	public void getRooms(){
		try {
			curUser.getRooms().clear();
			if(!"".equals(roomsUrl)){
				TERequest rq=new TERequest( Xmnn.COOKIE_PREFIX+curUser.getUser(),
						roomsUrl, TERequest.METHOD_GET,"gb2312", "gb2312");
				doConnect(getRoomsLisener,rq,iapp.getProxy());
			}
		} catch (Exception e) {
			logError.error("获取房间失败",e);
		}
	}
	public void enterRoom(){
		try {
			if(curUser.getRooms().size()<=0){
				logInfo.info(curUser.getUser()+",今日已参与完所有的博饼区");
				return;
			}
			curRooms=curUser.getRooms().remove(0);
			System.out.println(curUser.getUser()+",还有"+curUser.getRooms().size()+"个包间");
			String url=new UrlUtils(roomUrl).setObject("rid",curRooms).toString();
			System.out.println(curUser.getUser()+"进入包间："+url);
			TERequest rq=new TERequest( Xmnn.COOKIE_PREFIX+curUser.getUser(),
					url, TERequest.METHOD_GET,"gb2312", "gb2312");
			doConnect(enterRoomLisener,rq,iapp.getProxy());
		} catch (Exception e) {
			logError.error("切换包间失败",e);
		}
	}
	public void loginRooms(){
		try {
			Map<String, String> param=new HashMap<String, String>();
			param.put("type","厦门网会员");
			param.put("username",curUser.getUser());
			param.put("password", curUser.getPass());
			TERequest rq=new TERequest( Xmnn.COOKIE_PREFIX+curUser.getUser(),
					roomsLogin, TERequest.METHOD_POST,"utf-8", "gb2312");
			doConnect(roomloginLisener,rq,iapp.getProxy());
		} catch (Exception e) {
			logError.error("切换包间失败",e);
		}
	}
	public void boyiba(){
		try {
			int index=0;
			if(willCore.size()>0){
				index=willCore.remove(0);
			}
			String str="很遗憾，没有获奖，继续努力！";
			String rs="";
			String point="";
			if(index==6){
				index=6+rand.nextInt(5);
			}else if(index==11){
				index=11+rand.nextInt(1);
			}
			Core core=Core.getCore(index);
			if(index>0){
				str="恭喜您！您博得了";
				rs=core.getStr();
				point=core.getCore();
				if(index==6){
					rs+=zhuanyuan[rand.nextInt(zhuanyuan.length)];
				}else if(index==7){
					rs+=wuzi[rand.nextInt(wuzi.length)];
				}
			}
			TERequest rq=new TERequest( Xmnn.COOKIE_PREFIX+curUser.getUser(),
					boUrl, TERequest.METHOD_POST,"gb2312", "gb2312");
			rq.addParam("roomid",curRooms);
			rq.addParam("cardno","undefined");
			rq.addParam("username",curUser.getUser());
			rq.addParam("point",point);
			rq.addParam("rs",rs);
			rq.addParam("str", str);
			doConnect(boyibaLisener,rq,iapp.getProxy());
			logInfo.info(curUser.getUser()+",房间:"+curRooms+","+str+ rs+(point.equals("")?"":",博饼分:"+point)+",还有包间:"+curUser.getRooms().size()+"还能博:"+willCore.size());
		} catch (Exception e) {
			logError.error("博一把出错",e);
		}
	}
	public void taskError(String error, Exception e) {
		logError.error("博饼异常",e);
	}
	public void taskCore() throws Exception {
		if(rooms!=null && !"".equals(rooms)){
			logInfo.info("走指定的房间:"+rooms);
			String[] roomls=rooms.split(",");
			for (int j = 0; j < roomls.length; j++) {
				if(!"".equals(roomls[j].trim())){
					curUser.getRooms().add(roomls[j]);
				}
			}
			enterRoom();
		}else{
			getRooms();
		}
	}
	public void taskDestroy() throws Exception {
	}
	private void initLiseners(){
		if(getRoomsLisener==null){
			getRoomsLisener=new IBrowserLisener(){
				public void doException(String msg,Exception e){
					logError.error(msg,e);
					gotoSleep(2+rand.nextInt(2));
					getRooms();
				}
				public void response(String resp)
				{
					curUser.getRooms().clear();
					Document doc = Jsoup.parse(resp,"gb2312");
					Elements elements=doc.getElementsByClass("fr");
					if(elements!=null && !elements.isEmpty()){
						Element e=elements.get(0);
						Elements es = e.getElementsByTag("dl");
						if(es==null || es.isEmpty()){
							logInfo.info("没有找到相应的博饼区");
						}
						for(Element e2:es){
							Elements es2 = e2.getElementsByTag("dd");
							if(es2==null||es2.isEmpty())continue;
							Element e3=es2.get(0);
							Elements es3 =e3.getElementsByTag("a");
							if(es3==null||es3.isEmpty())continue;
							String link=es3.get(0).attr("href");
							if (!"".equals(link)&&link.indexOf("room.php?roomid=")>=0){
								String roomid=link.substring(link.indexOf("room.php?roomid=")+"room.php?roomid=".length());
								curUser.getRooms().add(roomid);
							}
						}
						if(curUser.getRooms().size()>0){
							genCores(curUser.getWillCore(),curUser.getRooms().size()*10);
							gotoSleep(2+rand.nextInt(2));
						}
						enterRoom();
					}else{
						logError.error("返回内容有误:\n"+resp);
					}
				}
			};
		}
		if(enterRoomLisener==null){
			enterRoomLisener=new IBrowserLisener(){
				public void doException(String msg,Exception e){
					logError.error(msg,e);
					curUser.getRooms().add(curRooms);
					gotoSleep(3+rand.nextInt(3));
					enterRoom();
				}
				public void response(String resp)
				{
					Document doc = Jsoup.parse(resp,"gb2312");
					if(doc.getElementById("object_id")!=null){
						gotoSleep(4+rand.nextInt(4));
						loginRooms();
					}
				}
			};
		}
		if(roomloginLisener==null){
			roomloginLisener=new IBrowserLisener(){
				public void doException(String msg,Exception e){
					logError.error(msg,e);
					curUser.getRooms().add(curRooms);
					gotoSleep(3+rand.nextInt(3));
					enterRoom();
				}
				public void response(String resp)
				{
					if("0".equals(resp)){
						logInfo.info("博饼区登录出错");
					}else{
						logInfo.info("博饼区已成功登录");
						gotoSleep(3+rand.nextInt(3));
						boyiba();
					}
				}
			};
		}
		if(boyibaLisener==null){
			boyibaLisener=new IBrowserLisener(){
				public void doException(String msg,Exception e){
					logError.error(msg,e);
					curUser.getRooms().add(curRooms);
					gotoSleep(3+rand.nextInt(3));
					enterRoom();
				}
				public void response(String resp)
				{
					if(resp.matches("[0-9]*")&&Integer.parseInt(resp)<10){
						gotoSleep(3+rand.nextInt(3));
						System.out.println("博饼分提交成功,返回次数:"+resp);
						boyiba();
					}else{
						gotoSleep(3+rand.nextInt(3));
						enterRoom();
					}
				}
			};
		}
	}
}
